package day06;

import java.util.Arrays;

//2. 扑克牌
//每张牌有花色和点数
//花色: 红桃, 黑桃, 方块, 梅花
//点数: A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K
//另加两张: 大王, 小王
//共54张
//定义方法分别实现以下功能
//1. 创建并初始化整副牌
//2. 洗牌: 将初始初始化好的整副牌顺序打乱
//3. 发牌: 将这副牌发给3个玩家, 每人17张手牌, 留3张底牌
//	分别输出每个玩家的手牌, 以及3张底牌
public class Demo02 {
	public static void main(String[] args) {

		String[] poker = new String[54];
		init(poker);
		System.out.println("初始化: "+Arrays.toString(poker));

		// poker = shuffle0(poker);
		shuffle(poker);
		System.out.println("洗牌后: "+Arrays.toString(poker));

		// 3个玩家, 每人17张手牌
		// 用3个长度为17的数组表示
		String[] p1 = new String[17];
		String[] p2 = new String[17];
		String[] p3 = new String[17];

		deal(poker, p1, p2, p3);

		System.out.println("p1的手牌: " + Arrays.toString(p1));
		System.out.println("p2的手牌: " + Arrays.toString(p2));
		System.out.println("p3的手牌: " + Arrays.toString(p3));
		System.out.println("底牌");
		System.out.println(poker[51]);
		System.out.println(poker[52]);
		System.out.println(poker[53]);

	}

	// 初始化54张卡牌, 存入poker
	public static void init(String[] poker) {

		String[] color = { "红桃", "黑桃", "方块", "梅花" };
		String[] pointer = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };

		int index = 0;

		for (int i = 0; i < color.length; i++) {
			for (int j = 0; j < pointer.length; j++) {
				poker[index++] = color[i] + pointer[j];
			}
		}

		poker[52] = "大王";
		poker[53] = "小王";

	}

	// 洗牌

	// 思路
	// 方案1
	// 创建一个空牌盒
	// 从旧牌盒中随机抽取卡牌
	// 向新牌盒中存放
	public static String[] shuffle0(String[] poker) {
		String[] tmp = new String[poker.length];

		for (int i = 0; i < tmp.length; i++) {
			int ran;
			do {
				ran = (int) (Math.random() * poker.length);
			} while (poker[ran] == null);
			tmp[i] = poker[ran];
			poker[ran] = null;
		}

		return tmp;

	}

	public static void shuffle(String[] poker) {
		// 方案2
		// 将每个位置上的牌, 与整副牌中随机位置的牌互换
		// 每张牌都换一遍之后, 整副牌就变成乱序的了
		for (int i = 0; i < poker.length; i++) {
			int ran;
			do {
				ran = (int) (Math.random() * poker.length);
			} while (ran == i);

			String tmp = poker[i];
			poker[i] = poker[ran];
			poker[ran] = tmp;
		}

	}

	// 发牌
	public static void deal(String[] poker, String[] p1, String[] p2, String[] p3) {
		int index = 0;
		for (int i = 0; i < 17; i++) {
			p1[i] = poker[index++];
			p2[i] = poker[index++];
			p3[i] = poker[index++];
		}

	}

}
